/*
 * @Author: jianglijun 
 * @Date: 2019-04-20 21:30:18 
 * @Last Modified by: jianglijun
 * @Last Modified time: 2019-04-20 23:39:57
 */

 /****************  遍历路由文件   *************** */
exports.getRouter = function(params) {
    const router = require('koa-router')()
    const fs = require('fs')
    const path = require('path')
    params = path.resolve(__dirname,"../routes/",params);
    const files = fs.readdirSync(params)
    files
        .filter(file => ~file.search(/^[^\.].*\.js$/))
        .forEach(file => {
            const file_name = file.substr(0, file.length - 3);
            const file_entity = require(path.join(params, file));
            if (file_name !== 'index') {
                router.use(`/${file_name}`, file_entity.routes(), file_entity.allowedMethods())
            }
        })
    
    return router;
}

/*******************  返回与api同目录文件 ********************* */
exports.getDir = function (dir) {
    return require("path").join(__dirname, '..', dir)
}

/****************** 数组与数组是否包含*************************** */
exports.isContained = function (aa, bb,flag=true) {
    //flag true 表示 两个数组要求长度一直
	if(!(aa instanceof Array) || !(bb instanceof Array) || ((aa.length < bb.length))) {
		return false;
	}
	if(flag){
        if(aa.length != bb.length){
            return false;
        }
    }
	for (var i = 0; i < bb.length; i++) {
		var flag = false;
		for(var j = 0; j < aa.length; j++){
			if(aa[j] == bb[i]){
				flag = true;
                break;
			}
		}
		if(flag == false){
			return flag;
		}
	}
	
	return true;
}

/****************** 传递JSON *************************** */
exports.tranJson = function (param) {
    let str = Object.keys(param)[0];
    return eval("(" + str + ")");    
}